export function setup() {
  $data.gua64ByBinary = $data.gua64.reduce((obj, item, index) => {
    obj[item.binary] = index;
    return obj;
  }, {});
  $data.gua64ByNo = $data.gua64.reduce((obj, item, index) => {
    obj[item.zhouYiNo] = index;
    return obj;
  }, {});
  $data.gua8XianTianList = $data.gua8XianTianSort.map((name) => {
    const gua = $data.gua8.find(g => g.names.includes(name))
    return gua8To64(gua.binary, gua.binary);
  });

  $data.gua8GongList = $data.gua8GongSort.map((name) => {
    const gua = $data.gua8.find(g => g.names.includes(name))
    return gua8To64(gua.binary, gua.binary);
  });

  $data.gua64GongList = $data.gua8GongList.map(item => get8BianList(item)).flat();

  const gua8List = $data.gua8XianTianList.map(item => item.binary.substring(0, 3)).reverse();
  $data.gua64XianTianList = gua8List.map((b1) => gua8List.map(b2 => gua8To64(b2, b1))).flat();
  

}

export function findByBinary(binary) {
  const index = $data.gua64ByBinary[binary];
  if (index === undefined) {
    return undefined;
  }
  return $data.gua64[index];
}

export function findByNo(no) {
  const index = $data.gua64ByNo[no];
  if (index === undefined) {
    return undefined;
  }
  return $data.gua64[index];
}

export function gua8To64(up, down) {
  return findByBinary(up + down)
}

export function get8BianList(gua) {
  let binary = gua.binary
  
  const binarys = [binary]
  binary = updateYao(binary, [1])
  binarys.push(binary)
  binary = updateYao(binary, [2])
  binarys.push(binary)
  binary = updateYao(binary, [3])
  binarys.push(binary)
  binary = updateYao(binary, [4])
  binarys.push(binary)
  binary = updateYao(binary, [5])
  binarys.push(binary)
  binary = updateYao(binary, [4])
  binarys.push(binary)
  binary = updateYao(binary, [3, 2, 1])
  binarys.push(binary)
  return binarys.map(item => findByBinary(item))
}

export function updateYao(binary, yaoList) {
  return Array.from(binary).reverse().map((val, index) => {
    if (yaoList.includes(index + 1)) {
      val = val === '1' ? '0' : '1'
    }
    return val
  }).reverse().join('')
}

export function getBianYao(b1, b2) {
  const result = []
  for (let i = 0; i < 6; i++) {
    if (b1.charAt(i) !== b2.charAt(i)) {
      result.push(6 - i)
    }
  }
  return result
}

/**
 * 错卦
 */
export function getCuoGua(binary) {
  const cuoBinary = updateYao(binary, [1, 2, 3, 4, 5, 6])
  return findByBinary(cuoBinary)
}

/**
 * 综卦
 */
export function getZongGua(binary) {
  const zongBinary = Array.from(binary).reverse().join('')
  return findByBinary(zongBinary)
}

/**
 * 复卦
 */
export function getFuGua(binary) {
  const fuBinary = binary.substr(2, 3) + binary.substr(1, 3)
  return findByBinary(fuBinary)
}